package com.example.victory.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.victory.config.ServiceError;
import com.example.victory.entity.companyEntity.H5Entity;
import com.example.victory.mapper.CustomerMapper;
import com.example.victory.mapper.OrgMapper;
import com.example.victory.mapper.RoleMapper;
import com.example.victory.mapper.UserMapper;
import com.example.victory.swagger.handler.InnerApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.victory.swagger.model.ApiResponseNull;
import com.example.victory.utils.JsonUtils;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequesFsdp;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequesFsdpData;
import com.cgws.fintech.sdk.api.inner.crmapi.model.ApiResponseFsdp;
import com.cgws.fintech.sdk.api.inner.security.model.*;
import com.cgws.fintech.sdk.api.mvp.model.ApiRequestEmployeeQuery;
import com.cgws.fintech.sdk.api.mvp.model.ApiResponseEmployeeQuery;
import com.cgws.fintech.sdk.api.mvp.model.SysAccount;
import com.cgws.fintech.sdk.common.cache.RedisService;
import com.cgws.fintech.sdk.common.exception.GlobalError;
import com.cgws.fintech.sdk.common.exception.GlobalException;
import com.cgws.fintech.sdk.common.utils.DateHelper;
import com.cgws.fintech.sdk.common.utils.MoneyHelper;
import com.example.victory.common.web.ServiceHelper;
import com.cgws.fintech.sdk.inner.utils.web.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class InnerApiService implements InnerApiDelegate {

	@Autowired
	private SessionService sessionService;

	@Autowired
	private CustomerMapper customerMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private OrgMapper orgMapper;

	@Autowired
	private RoleMapper roleMapper;

	@Autowired
	private MvpLoginService mvpLoginService;

	@Autowired
	private InnerService innerService;

	@Autowired
	private InnerH5FsdpService innerH5FsdpService;

	@Autowired
	private RedisService redisService;

	@Autowired
	private InnerCrmApiService customerApi;

	/**
	 * 获取CRM客户的所属投顾列表
	 *
	 * @param param 请求参数
	 * @return 请求结果
	 */
	@Override
	public ResponseEntity<ApiResponseCrmUsersInfo> getCrmAdvisors(ApiRequestCustomerId param) {
		String customerId = param.getData().getCustomerId();
		ServiceHelper.checkDataNotNull(customerId, "customerId");
		ApiResponseCrmUsersInfoData apiResponseCrmUsersInfoData = userMapper.findUsersByCustomerId(customerId);
		return ResponseEntity.ok(new ApiResponseCrmUsersInfo().data(apiResponseCrmUsersInfoData));
	}

	@Override
	public ResponseEntity<ApiResponseCrmBrokersClients> getCrmBrokersClients(ApiRequestCrmBrokersClients param) {
		String userId = param.getData().getUserId();
		int count = userMapper.getBrokersClientsByUserId(userId);
		ApiResponseCrmBrokersClientsData crmBrokersClientsData = new ApiResponseCrmBrokersClientsData();
		crmBrokersClientsData.setIsBrokersClients(count > 0 ? Boolean.TRUE : Boolean.FALSE);
		return ResponseEntity.ok(new ApiResponseCrmBrokersClients().data(crmBrokersClientsData));
	}

	/**
	 * 金额转换为千分位
	 *
	 * @param money
	 * @return
	 */
	private static String formatMoneyThousandth(String money) {
		if (!money.contains(".")) {
			return money.replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ",");
		}
		String moneyStr = money.substring(0, money.indexOf("."));
		String result = moneyStr.replaceAll("(?<=\\d)(?=(?:\\d{3})+$)", ",");
		String moneyLength = money.substring(money.indexOf("."));
		return result + moneyLength;
	}

	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmCustomers() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		getCustomerAccount(user);
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		try {
			String result = customerApi.getCustomerQuantity().getBody().getData().getResult();
			crmCustomersDataNameValue.setValue(formatMoneyThousandth(JSON.parseObject(result).getString("customerQuantity")));
		} catch (Exception e) {
			log.error("通过fsdp获取客户数出错",e);
			crmCustomersDataNameValue.setValue("0");
		}
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));

	}

	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmCustomersCaptial() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(MoneyHelper.formatMoney(customerMapper.getCustomersAssetTotal(accountId))));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}

	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmCustomersCaptialDev() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(MoneyHelper.formatMoney(customerMapper.getCustomersAssetTotalByType(accountId, 10))));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}

	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmCustomersCaptialService() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(MoneyHelper.formatMoney(customerMapper.getCustomersAssetTotalByType(accountId, 1))));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}


	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmCustomersDev() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(customerMapper.getCustomersCountByType(accountId, 10).toString()));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}

	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmCustomersService() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(customerMapper.getCustomersCountByType(accountId, 1).toString()));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}


	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmDept() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(customerMapper.getDeptCustomersTotal(accountId).get("CUSTOMERTOTAL")));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}

	@Override
	public ResponseEntity<ApiResponseCrmCustomers> getCrmDeptCaptial() {
		User user = sessionService.getCurrentUserSession(true).getUser();
		Integer accountId = getCustomerAccount(user);
		ApiResponseCrmCustomersData crmCustomersData = new ApiResponseCrmCustomersData();
		List<ApiResponseCrmCustomersData> nameValue = new ArrayList<>();
		ApiResponseCrmCustomersData crmCustomersDataNameValue = new ApiResponseCrmCustomersData();
		crmCustomersDataNameValue.setValue(formatMoneyThousandth(MoneyHelper.formatMoney(new BigDecimal(customerMapper.getDeptCustomersTotal(accountId).get("TOTAL")))));
		nameValue.add(crmCustomersDataNameValue);
		return ResponseEntity.ok(new ApiResponseCrmCustomers().data(nameValue));
	}

	@Override
	public ResponseEntity<ApiResponseCrmMarketDay> getCrmMarketDay(ApiRequestCrmMarketDay param) {
		ApiRequestCrmMarketDayData crmMarketDayData = param.getData();
		String dateStr = null;
		if (crmMarketDayData != null && !StringUtils.isEmpty(crmMarketDayData.getDate())) {
			dateStr = crmMarketDayData.getDate();
			if (dateStr.length() != 8) {
				throw new GlobalException(ServiceError.QUERY_MARKET_DAY_ERROR);
			}
		} else {
			dateStr = DateHelper.getDateYYYYMMDD(new Date());
		}

		String dateMarket = customerMapper.getCrmMarketDay(dateStr);
		if (StringUtils.isEmpty(dateMarket)) {
			dateMarket = customerMapper.getCrmMarketDay(DateHelper.getDateYYYYMMDD(new Date()));
		}
		ApiResponseCrmMarketDayData apiResponseCrmMarketDayData = new ApiResponseCrmMarketDayData();
		apiResponseCrmMarketDayData.setDate(dateMarket);

		return ResponseEntity.ok(new ApiResponseCrmMarketDay().data(apiResponseCrmMarketDayData));
	}

	private Integer getCustomerAccount(User user) {
		String crmId = user.getCrmId();
		if (StringUtils.isEmpty(crmId)) {
			throw new GlobalException(ServiceError.ACCOUNT_NOT_EXISTS);
		}
		return Integer.parseInt(crmId);

	}

	@Override
	public ResponseEntity<ApiResponseCustomerPhone> getCrmCustomerFcid(ApiRequestCustomerPhone param) {
		String customerId = param.getData().getCustomerId();
		ServiceHelper.checkDataNotNull(customerId, "customerId");
		ApiResponseCrmUsersInfoData apiResponseCrmUsersInfoData = userMapper.findUsersByCustomerId(customerId);
		if (apiResponseCrmUsersInfoData == null) {
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_ATTEND_INFO, customerId);
		}
		ApiResponseCustomerPhoneData customerPhoneData = new ApiResponseCustomerPhoneData();
		ApiRequestEmployeeQuery employeeQuery = new ApiRequestEmployeeQuery();
		List<SysAccount> sysAccountList = new ArrayList<>();
		SysAccount oaSysAccount = new SysAccount();
		oaSysAccount.setSysId("1");
		oaSysAccount.setStaffId(apiResponseCrmUsersInfoData.getId());
		sysAccountList.add(oaSysAccount);
		SysAccount crmSysAccount = new SysAccount();
		crmSysAccount.setSysId("2");
		crmSysAccount.setStaffId(apiResponseCrmUsersInfoData.getId());
		sysAccountList.add(crmSysAccount);

		employeeQuery.setData(sysAccountList);
		ResponseEntity<ApiResponseEmployeeQuery> employeeQueryResponseEntity = null;
		try {
			employeeQueryResponseEntity = mvpLoginService.queryStaffs(employeeQuery);
			if (employeeQueryResponseEntity.getStatusCode() == HttpStatus.OK && employeeQueryResponseEntity.getBody().getData() != null && employeeQueryResponseEntity.getBody().getData().getList() != null && employeeQueryResponseEntity.getBody().getData().getList().size() > 0) {
				List<SysAccount> sysAccounts = employeeQueryResponseEntity.getBody().getData().getList();
				sysAccounts.stream().forEach(sysAccount -> {
					String fcid = sysAccount.getFcid();
					if (!StringUtils.isEmpty(sysAccount.getFcid()) && sysAccount.getSysId().equals("2")) {
						customerPhoneData.setFcid(fcid);
						return;
					} else if (!StringUtils.isEmpty(sysAccount.getFcid()) && sysAccount.getSysId().equals("1")) {
						customerPhoneData.setFcid(fcid);
					}
				});
				if (StringUtils.isEmpty(customerPhoneData.getFcid())) {
					//没有绑定
					ApiRequestAccount apiRequestAccount = new ApiRequestAccount();
					ApiRequestAccountData apiRequestAccountData = new ApiRequestAccountData();
					apiRequestAccountData.setAccount(apiResponseCrmUsersInfoData.getId());
					apiRequestAccount.setData(apiRequestAccountData);
					ResponseEntity<ApiResponseFcid> fcidByAccountInner = innerService.getFcidByAccountInner(apiRequestAccount);
					log.info("响应参数:{}", fcidByAccountInner);
					if (fcidByAccountInner.getStatusCode() != HttpStatus.OK) {
						throw new GlobalException(ServiceError.QUERY_FCID_ATTEND_INFO);
					}
					if (fcidByAccountInner.getBody().getData() != null && !StringUtils.isEmpty(fcidByAccountInner.getBody().getData().getFcid())) {
						customerPhoneData.setFcid(fcidByAccountInner.getBody().getData().getFcid());
					}
				}
			}
		} catch (Exception ex) {
			log.error("请求MVP的员工账号集合获取员工详情列表失败,e={}", ex);
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_DETAIL_INFO);
		}
		return ResponseEntity.ok(new ApiResponseCustomerPhone().data(customerPhoneData));
	}

	@Override
	public ResponseEntity<ApiResponseCustomerPhone> getCrmCustomerRelationsType(ApiRequestCustomerPhone param) {
		String customerId = param.getData().getCustomerId();
		ServiceHelper.checkDataNotNull(customerId, "customerId");
		ApiResponseCrmUsersInfoData apiResponseCrmUsersInfoData = userMapper.findUsersByCustomerId(customerId);
		if (apiResponseCrmUsersInfoData == null) {
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_ATTEND_INFO, customerId);
		}
		ApiResponseCustomerPhoneData customerPhoneData = new ApiResponseCustomerPhoneData();
		ApiRequestEmployeeQuery employeeQuery = new ApiRequestEmployeeQuery();
		List<SysAccount> sysAccountList = new ArrayList<>();
		SysAccount oaSysAccount = new SysAccount();
		oaSysAccount.setSysId("1");
		oaSysAccount.setStaffId(apiResponseCrmUsersInfoData.getId());
		sysAccountList.add(oaSysAccount);
		SysAccount crmSysAccount = new SysAccount();
		crmSysAccount.setSysId("2");
		crmSysAccount.setStaffId(apiResponseCrmUsersInfoData.getId());
		sysAccountList.add(crmSysAccount);

		employeeQuery.setData(sysAccountList);
		ResponseEntity<ApiResponseEmployeeQuery> employeeQueryResponseEntity = null;
		try {
			employeeQueryResponseEntity = mvpLoginService.queryStaffs(employeeQuery);
			if (employeeQueryResponseEntity.getStatusCode() == HttpStatus.OK && employeeQueryResponseEntity.getBody().getData() != null && employeeQueryResponseEntity.getBody().getData().getList() != null && employeeQueryResponseEntity.getBody().getData().getList().size() > 0) {
				List<SysAccount> sysAccounts = employeeQueryResponseEntity.getBody().getData().getList();
				sysAccounts.stream().forEach(sysAccount -> {
					String fcid = sysAccount.getFcid();
					if (!StringUtils.isEmpty(sysAccount.getFcid()) && sysAccount.getSysId().equals("2")) {
						customerPhoneData.setFcid(fcid);
						return;
					} else if (!StringUtils.isEmpty(sysAccount.getFcid()) && sysAccount.getSysId().equals("1")) {
						customerPhoneData.setFcid(fcid);
					}
				});
				if (StringUtils.isEmpty(customerPhoneData.getFcid())) {
					//没有绑定
					ApiRequestAccount apiRequestAccount = new ApiRequestAccount();
					ApiRequestAccountData apiRequestAccountData = new ApiRequestAccountData();
					apiRequestAccountData.setAccount(apiResponseCrmUsersInfoData.getId());
					apiRequestAccount.setData(apiRequestAccountData);
					ResponseEntity<ApiResponseFcid> fcidByAccountInner = innerService.getFcidByAccountInner(apiRequestAccount);
					log.info("响应参数:{}", fcidByAccountInner);
					if (fcidByAccountInner.getStatusCode() != HttpStatus.OK) {
						throw new GlobalException(ServiceError.QUERY_FCID_ATTEND_INFO);
					}
					if (fcidByAccountInner.getBody().getData() != null && !StringUtils.isEmpty(fcidByAccountInner.getBody().getData().getFcid())) {
						customerPhoneData.setFcid(fcidByAccountInner.getBody().getData().getFcid());
					}
				}
			}
		} catch (Exception ex) {
			log.error("请求MVP的员工账号集合获取员工详情列表失败,e={}", ex);
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_DETAIL_INFO);
		}
		return ResponseEntity.ok(new ApiResponseCustomerPhone().data(customerPhoneData));
	}

	@Override
	public ResponseEntity<ApiResponseCustomerPhone> getCrmCustomerRelations(ApiRequestCustomerPhone param) {
		String customerId = param.getData().getCustomerId();
		ServiceHelper.checkDataNotNull(customerId, "customerId");
		ApiResponseCrmUsersInfoData apiResponseCrmUsersInfoData = userMapper.findUsersByCustomerId(customerId);
		if (apiResponseCrmUsersInfoData == null) {
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_ATTEND_INFO, customerId);
		}
		ApiResponseCustomerPhoneData customerPhoneData = new ApiResponseCustomerPhoneData();
		ApiRequestEmployeeQuery employeeQuery = new ApiRequestEmployeeQuery();
		List<SysAccount> sysAccountList = new ArrayList<>();
		SysAccount oaSysAccount = new SysAccount();
		oaSysAccount.setSysId("1");
		oaSysAccount.setStaffId(apiResponseCrmUsersInfoData.getId());
		sysAccountList.add(oaSysAccount);
		SysAccount crmSysAccount = new SysAccount();
		crmSysAccount.setSysId("2");
		crmSysAccount.setStaffId(apiResponseCrmUsersInfoData.getId());
		sysAccountList.add(crmSysAccount);

		employeeQuery.setData(sysAccountList);
		ResponseEntity<ApiResponseEmployeeQuery> employeeQueryResponseEntity = null;
		try {
			employeeQueryResponseEntity = mvpLoginService.queryStaffs(employeeQuery);
			if (employeeQueryResponseEntity.getStatusCode() == HttpStatus.OK && employeeQueryResponseEntity.getBody().getData() != null && employeeQueryResponseEntity.getBody().getData().getList() != null && employeeQueryResponseEntity.getBody().getData().getList().size() > 0) {
				List<SysAccount> sysAccounts = employeeQueryResponseEntity.getBody().getData().getList();
				sysAccounts.stream().forEach(sysAccount -> {
					String fcid = sysAccount.getFcid();
					if (!StringUtils.isEmpty(sysAccount.getFcid()) && sysAccount.getSysId().equals("2")) {
						customerPhoneData.setFcid(fcid);
						return;
					} else if (!StringUtils.isEmpty(sysAccount.getFcid()) && sysAccount.getSysId().equals("1")) {
						customerPhoneData.setFcid(fcid);
					}
				});
				if (StringUtils.isEmpty(customerPhoneData.getFcid())) {
					//没有绑定
					ApiRequestAccount apiRequestAccount = new ApiRequestAccount();
					ApiRequestAccountData apiRequestAccountData = new ApiRequestAccountData();
					apiRequestAccountData.setAccount(apiResponseCrmUsersInfoData.getId());
					apiRequestAccount.setData(apiRequestAccountData);
					ResponseEntity<ApiResponseFcid> fcidByAccountInner = innerService.getFcidByAccountInner(apiRequestAccount);
					log.info("响应参数:{}", fcidByAccountInner);
					if (fcidByAccountInner.getStatusCode() != HttpStatus.OK) {
						throw new GlobalException(ServiceError.QUERY_FCID_ATTEND_INFO);
					}
					if (fcidByAccountInner.getBody().getData() != null && !StringUtils.isEmpty(fcidByAccountInner.getBody().getData().getFcid())) {
						customerPhoneData.setFcid(fcidByAccountInner.getBody().getData().getFcid());
					}
				}
			}
		} catch (Exception ex) {
			log.error("请求MVP的员工账号集合获取员工详情列表失败,e={}", ex);
			throw new GlobalException(ServiceError.QUERY_CUSTOMER_DETAIL_INFO);
		}
		return ResponseEntity.ok(new ApiResponseCustomerPhone().data(customerPhoneData));
	}

	/**
	 * 获取所有组织
	 *
	 * @return 请求结果
	 */
	@Override
	public ResponseEntity<ApiResponseCrmOrgs> getCrmOrgs() {
		List<CrmOrg> orgs = orgMapper.getAll();
		return ResponseEntity.ok(new ApiResponseCrmOrgs().data(new ApiResponseCrmOrgsData().items(orgs)));
	}

	/**
	 * 获取所有角色
	 *
	 * @return 请求结果
	 */
	@Override
	public ResponseEntity<ApiResponseCrmRoles> getCrmRoles() {
		List<CrmRole> roles = roleMapper.getAll();
		return ResponseEntity.ok(new ApiResponseCrmRoles().data(new ApiResponseCrmRolesData().items(roles)));
	}

	@Override
	public ResponseEntity<ApiResponseCrmUserId> getCrmUserId(ApiRequestCrmUserId param) {
		String crmId = param.getData().getCrmId();
		ServiceHelper.checkDataNotNull(crmId, "crmId");
		ApiResponseCrmUserIdData apiResponseCrmUserIdData = userMapper.findUsersIdByTryxxId(crmId);
		return ResponseEntity.ok(new ApiResponseCrmUserId().data(apiResponseCrmUserIdData));
	}

	/**
	 * 获取CRM用户列表
	 *
	 * @return 请求结果
	 */
	@Override
	public ResponseEntity<ApiResponseCrmUsers> getCrmUsers() {
		List<CrmUser> crmUsers = userMapper.findUsers();
		if (crmUsers != null) {
			HashMap<String, CrmUser> map = new HashMap<>();
			crmUsers.forEach(item -> {
				map.put(item.getCrmid(), item);
			});
			List<CrmJjrbh> crmJjrbhs = userMapper.findCrmJjrbh();
			if (crmJjrbhs != null) {
				crmJjrbhs.forEach(item -> {
					String key = String.valueOf(item.getCrmId());
					if (map.containsKey(key)) {
						map.get(key).setJjrbh(item.getJjrbh());
					}
				});
			}
		}

		return ResponseEntity.ok(new ApiResponseCrmUsers().data(new ApiResponseCrmUsersData().items(crmUsers)));
	}

	/**
	 * 获取经纪人编号
	 *
	 * @return 经纪人编号
	 */
	@Override
	public ResponseEntity<ApiResponseCrmJjrbh> getCrmJjrbh() {
		List<CrmJjrbh> crmJjrbhs = userMapper.findCrmJjrbh();
		return ResponseEntity.ok(new ApiResponseCrmJjrbh().data(new ApiResponseCrmJjrbhData().items(crmJjrbhs)));
	}


	@Override
	public ResponseEntity<ApiResponseNull> getRelationshipOfCustomerAndManager(ApiRequestRelationshipOfCustomerAndManager param) {
		ApiRequestRelationshipOfCustomerAndManagerData customerManagerData = param.getData();
		ServiceHelper.checkDataNotNull(customerManagerData.getAccount(), "data.account");
		ServiceHelper.checkDataNotNull(customerManagerData.getSessionId(), "data.sessionId");
		String account = customerManagerData.getAccount();
		String crmId = null;
		try {
			String sessionId = customerManagerData.getSessionId();
			if (sessionId == null) {
				throw new GlobalException(GlobalError.PLATFORM_SECURITY_UNLOGIN);
			}
			Session session = sessionService.getSession(sessionId);
			if (session == null) {
				// token过期
				throw new GlobalException(GlobalError.PLATFORM_SECURITY_TOKEN_TIMEOUT);
			}
			User user = (User) redisService.getRedisTemplate().opsForHash().get("inner-platform-security:alluser:id", String.valueOf(session.getUserid()));
			log.info("打印根据userid={}，获取的用户信息={}", session.getUserid(), user);
			if (StringUtils.isEmpty(user.getCrmId())) {
				throw new GlobalException(ServiceError.ACCOUNT_NOT_EXISTS);
			}
			crmId = user.getCrmId();
		} catch (Exception e) {
			log.error("判断当前资金账号是或否该客户经理异常，e={}", e);
			throw new GlobalException(ServiceError.ACCOUNT_NOT_EXISTS);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("crmId", crmId);
		jsonObject.put("account", account);
		ResponseEntity<ApiResponseFsdp> fsdpResponseEntity = innerH5FsdpService.getCustomerManager(new ApiRequesFsdp().data(new ApiRequesFsdpData().params(jsonObject.toJSONString())));
		H5Entity manager = JsonUtils.getResultEntity(fsdpResponseEntity, H5Entity.class);
		if (manager == null || manager.getManager().equalsIgnoreCase("no")) {
			throw new GlobalException(ServiceError.QUERY_FSDP_MANAGER_ERROR);
		}
		return ResponseEntity.ok(new ApiResponseNull());
	}
}
